from utils.ip2region.ip2Region import Ip2Region

db_file = r'utils/ip2region/ip2region.db'  # 数据库文件路径


def ip_search(ip):
    if ip:
        try:
            searcher = Ip2Region(db_file)  # 实例化
            searcher.isip(ip)
            # 三种算法任选其一
            # data = searcher.btreeSearch(ip)  # B树
            # data = searcher.binarySearch(ip) #二进制
            data = searcher.memorySearch(ip)  # 内存
            # print(data)
            # print("%s|%s" % (ip, data["region"].decode('utf-8')))
            searcher.close()
            result = data["region"].decode('utf-8')
            result_li = result.split('|')
            result_li = [res for res in result_li if res != '0']
            result = '|'.join(result_li)
            return result
        except:
            return None
    return None


if __name__ == "__main__":
    ret = ip_search("183.14.31.250")
    print(ret)
    ret = ip_search("1.14.31.20")
    print(ret)
    ret = ip_search("18.164.31.20")
    print(ret)
    ret = ip_search("18.164.56.20")
    print(ret)
    ret = ip_search("18.135.56.20")
    print(ret)
    ret = ip_search("127.0.0.1")
    print(ret)
